如果還沒有看過我用Python寫出Bubble Sort程式的話,不妨可以點擊下方連結:
[Day 11]小型題材:Bubble Sort in Python
正式切入今天的主軸,也就是將物件導向的結構設計轉移到現有的程式中,所以就不光是要宣告初始輸入值的定義,更需要進一步去設定一些開放變數,就用實例來示範吧:
class BubbleSort(object):
after_sort = []
#其實這個物件內開放參數可以不用設,因為後面的方法內部又有Local參數可以取代
def __init__(self, list):
self.list = list
def sort(self):
self.after_sort = self.list
#就是這邊,其實不用去引用上面的開放參數,直接把值設定到指定物件
for x in range(0, len(self.after_sort) - 1):
booleaner = False
for y in range(0, len(self.after_sort) - 1):
if self.after_sort[y] > self.after_sort[y + 1]:
tmp = self.after_sort[y]
self.after_sort[y] = self.after_sort[y + 1]
self.after_sort[y + 1] = tmp
booleaner = True
if booleaner == True:
print("After " + str(x + 1) + " time(s) of exchange: " + str(self.after_sort))
else:
continue
def print_origin(self):
print("The original list: " + str(self.list))
def printer(self):
print("The result afte Bubble Sort is: " + str(self.after_sort))
#所以在這裡所印出來的after_sort並不是公開領域的after_sort,而是在經過起始設定之後指定出來的after_sort
test1 = BubbleSort([12,8,27,5,13,6,21])
test1.print_origin()
test1.sort()
#上面這行導出專屬於test1的after_sort,而不是預設(開放)參數的after_sort
test1.printer()
#同理,上面這行也是
#下面就是輸出結果:
#The original list: [12, 8, 27, 5, 13, 6, 21]
#After 1 time(s) of exchange: [8, 12, 5, 13, 6, 21, 27]
#After 2 time(s) of exchange: [8, 5, 12, 6, 13, 21, 27]
#After 3 time(s) of exchange: [5, 8, 6, 12, 13, 21, 27]
#After 4 time(s) of exchange: [5, 6, 8, 12, 13, 21, 27]
#The result afte Bubble Sort is: [5, 6, 8, 12, 13, 21, 27]